<template>
  <el-tabs tab-position="left" v-model="currentTab" @tab-click="handleTabClick">
    <!--职业概述-->
    <el-tab-pane label="职业概述">
      <div class="positionDesc">
        <div class="positionName">
          <span>{{positionName}}</span>
          <el-button class="switchBtn" size="small" type="primary" @click="changeEditStatus()" v-if="isAdmin == true">
            切换编辑模式
          </el-button>
        </div>
        <websocket ref="child" @initMessageBack="initMessageBack" />
        <div class="list">
          <el-row class="demo-autocomplete" v-for="item,index in this.info" :key="index">
            <el-col :span="21">
              <div class="controlLine">
                <span class="tinyTitle">
                  <div class="titleFlag"></div> {{ item.columnName }}
                </span>
                <div class="saveBtns">
                  <el-button size="small" class="rightBtn" @click="aiCreate(item.columnName,item.columnIndex)">
                    AI生成</el-button>
                  <el-button size="small" class="rightBtn" @click="copy(item.columnIndex)">一键复制</el-button>
                  <el-button size="small" class="rightBtn saveBtn"
                    @click="save(item.columnCode,item.columnIndex,item.table)"
                    v-if="isAdmin == true && editButtonStatus == true">
                    保存
                  </el-button>
                </div>
              </div>
              <div v-if="editButtonStatus == false" v-html="item.content" class="aiContent"></div>
              <div v-if="editButtonStatus == false" v-html="item.extendContent" class="aiExtendContent"></div>
              <el-input v-if="editButtonStatus == true" v-model="item.allContent" type="textarea" :rows="10" class="def"
                placeholder="请输入内容" />
            </el-col>
            <div height="1000px"></div>
          </el-row>
        </div>
      </div>
    </el-tab-pane>

    <!--        地区薪酬列表-->
    <el-tab-pane label="地区薪酬列表">
      <region-salary v-if="currentTab == 1" />
    </el-tab-pane>

    <!--        工作经验/薪酬列表-->
    <el-tab-pane label="工作经验薪酬列表">
      <work-salary v-if="currentTab == 2" />
    </el-tab-pane>
    <!--       学历薪酬-->
    <el-tab-pane label="学历薪酬列表">
      <education-salary v-if="currentTab == 3" />
    </el-tab-pane>
    <!--        求职者期望薪酬-->
    <el-tab-pane label="求职者期望薪酬">
      <expect-salary v-if="currentTab == 4" />
    </el-tab-pane>
    <!--        发展前景-->
    <el-tab-pane label="发展前景">
      <promotion-salary v-if="currentTab == 5" />
    </el-tab-pane>
    <el-tab-pane label="相似岗位薪酬">
      <SimilarPositionSalary v-if="currentTab == 6" />
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import {
  getInfo,
  getQuestionList,
  saveInfo,
  saveAnswerInfo,
} from "@/api/position-detail";
import Websocket from "@/components/Websocket";
import RegionSalary from "@/views/position/region_salary";
import WorkSalary from "@/views/position/work_salary";
import EducationSalary from "@/views/position/education_salary";
import ExpectSalary from "@/views/position/expect_salary";
import PromotionSalary from "@/views/position/promotion_salary";
import SimilarPositionSalary from "@/views/position/similar_position_salary";
import VueCookies from "vue-cookies";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

export default {
  name: "Detail",
  components: {
    PromotionSalary,
    ExpectSalary,
    EducationSalary,
    WorkSalary,
    RegionSalary,
    Websocket,
    Editor,
    Toolbar,
    SimilarPositionSalary,
  },
  data() {
    return {
      infoName: {
        def: { name: "岗位定义", order: 0 },
        task: { name: "工作内容", order: 1 },
        skill: { name: "推荐技能", order: 2 },
        book: { name: "推荐书籍", order: 3 },
        tool: { name: "推荐工具", order: 4 },
      },
      info: [],
      selfInfo: [],
      currentPositionName: "",
      positionName: "",
      positionId: 0,
      currentButton: null,
      chatKey: "",
      loading: false,
      isContinue: false,
      aiCreateStatus: false,
      isStoped: false,
      rebotBg: true,
      messageList: [],
      messages: [],
      showError: false,
      historyChatKey: "",
      isShowMore: false,
      currentMsg: "",
      currentRole: "",
      userId: "",
      userName: "",
      currentTab: "",
      isAdmin: false,
      editButtonStatus: false,

      editor: null,
      toolbarConfig: {},
      editorConfig: {
        placeholder: "请输入内容...",
        scroll: true,
      },
      mode: "simple", // or 'simple'
    };
  },
  mounted() {
    // this.fetchData()
    // 正常输出
  },
  created() {
    this.fetchData();
    this.positionName = this.$route.query.name;
  },
  methods: {
    handleTabClick() {},
    adminInit() {
      const userToken = VueCookies.get("vue_admin_template_token");
      // console.log(userToken)
      if (userToken === "admin-token") {
        this.isAdmin = true;
      }
    },
    fetchData() {
      this.adminInit();
      this.positionId = this.$route.query.id;
      this.currentPositionName = this.$route.query.name;

      getInfo({
        id: this.positionId,
      }).then((response) => {
        let i = 0;
        Object.entries(response.data).forEach(([key, value]) => {
          this.info.splice(i, 1, {
            columnName:
              this.infoName[key] != undefined ? this.infoName[key].name : "",
            columnCode: key,
            columnIndex:
              this.infoName[key] != undefined ? this.infoName[key].order : i,
            content: value.replace(/\n/g, "<br>"),
            allContent: value.replace(/\n/g, "<br>"),
            extendContent: "",
            table: "positionExtend",
          });
          i++;
        });
        this.info.sort(function (a, b) {
          return a.columnIndex - b.columnIndex;
        });

        getQuestionList({
          id: this.positionId,
        }).then((response) => {
          let j = 5;
          for (let i = 0; i < response.data.length; i++) {
            var answerContent =
              response.data[i].answer != null
                ? response.data[i].answer["answerContent"].replace(
                    /\n/g,
                    "<br>"
                  )
                : "";
            this.info.splice(j, 1, {
              columnName: response.data[i].questionContent,
              columnCode: response.data[i].id,
              columnIndex: j,
              content: answerContent,
              extendContent: "",
              allContent: answerContent,
              table: "positionQuestion",
            });
            j++;
          }
        });
      });
    },
    aiCreate(columnName, columnIndex) {
      if (this.aiCreateStatus) {
        this.$message({
          type: "warning",
          message:
            "已有AI正在生成中，等待生成内容结束或F5刷新页面再次点击AI生成!",
        });
        return;
      } else {
        this.aiCreateStatus = true;
      }
      const name =
        this.$route.query.name != undefined ? this.$route.query.name : "";
      this.chatKey = "写一段" + name + "的" + columnName;

      this.currentButton = columnIndex;
      // this.info[columnIndex].content = "";

      this.messages.push({
        role: "user",
        content: this.chatKey,
      });
      // console.log('AI')
      const agentData = {
        userId: "",
        userName: "",
        messages: this.messages,
      };
      this.messages = [];
      this.sendMsg = JSON.stringify(agentData);
      this.$refs.child.send(this.sendMsg, this.initMessageBack, this.wsError);
      this.$message.success({
        message: "AI生成内容中...",
        offset: "400",
      });
    },
    initMessageBack(res) {
      this.loading = true;
      // console.log('回调1')
      if (res === "err") {
        this.loading = false;
        return (this.showError = true);
      }
      const msg = res.choices && res.choices[0];
      if (!this.currentRole) {
        this.currentRole = msg.delta.role;
      }
      if (msg.delta.role === "assistant") {
        return;
      }
      if (msg.finish_reason === "stop" || msg.finish_reason === "done") {
        this.loading = false;
        this.currentMsg = "";
        this.currentRole = "";
        this.aiCreateStatus = false;
        this.info[this.currentButton].extendContent += "<br>";
        return;
      }
      var tempStr = msg.delta.content;
      tempStr = tempStr.replace(/(\r\n|\n|\r)+/g, "<br>");
      this.info[this.currentButton].extendContent += tempStr;
      this.info[this.currentButton].allContent += tempStr;
    },
    wsError() {
      if (this.isStoped) {
        this.isContinue = false;
      } else {
        this.isContinue = true;
      }
      //console.log("连接失败，请重试");
    },
    copy(columnIndex) {
      const input = document.createElement("input");
      var copyContent = this.info[columnIndex].allContent.replace(
        /<br[^>]+>/g,
        "\n"
      );
      console.log(copyContent);
      input.value = copyContent.replace(/<[^>]+>/g, "\n");
      input.id = "creatDom";
      document.body.appendChild(input);
      input.select();
      document.execCommand("copy");
      document.body.removeChild(input);
      this.$message.success({
        message: "复制成功！",
        offset: "400",
      });
    },
    changeEditStatus() {
      if (this.isAdmin) {
        this.editButtonStatus = !this.editButtonStatus;
      }
    },
    save(columnCode, columnIndex, table) {
      this.$confirm("此操作将覆盖原有内容, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.positionId = this.$route.query.id;
          const params = {
            ylPositionId: this.positionId,
          };
          if (table == "positionExtend") {
            var aiContent = this.info[columnIndex].allContent;
            switch (columnCode) {
              case "def":
                params.positionDefinition = aiContent;
                break;
              case "book":
                params.recommendBook = aiContent;
                break;
              case "task":
                params.workContent = aiContent;
                break;
              case "tool":
                params.recommendTool = aiContent;
                break;
              case "skill":
                params.recommendSkill = aiContent;
                break;
              default:
                this.$message({
                  type: "info",
                  message: "入参有误!",
                });
                break;
            }
            saveInfo(params).then((response) => {
              this.info[columnIndex].content =
                this.info[columnIndex].allContent;
              // console.log(response)
            });
          }

          if (table == "positionQuestion") {
            params.questionId = columnCode;
            params.answerContent = this.info[columnIndex].allContent;
            saveAnswerInfo(params).then((response) => {
              // console.log(response)
              this.info[columnIndex].content =
                this.info[columnIndex].allContent;
            });
          }

          this.$message({
            type: "success",
            message: "修改成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消修改",
          });
        });
    },
  },
};
</script>
<style scoped>
.list {
  overflow-y: auto;
  font-size: 15px;
}
.demo-autocomplete {
  margin-bottom: 50px;
}
.tinyTitle {
  display: flex;
  align-items: center;
  font-weight: bold;
  font-size: 18px;
  margin-right: 24px;
}
.positionName {
  display: flex;
  width: 100vw;
  align-items: center;
  color: #333333;
  background-color: #edf6ff;
  height: 48px;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 26px;
  margin-left: -56px;
  padding: 0 55px;
}
.switchBtn {
  margin-left: 12px;
}
.controlLine {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 12px;
}
.aiContent {
  line-height: 28px;
  letter-spacing: 1px;
  font-size: 15px;
  color: #606266;
}
.aiExtendContent {
  line-height: 28px;
  color: #1677db;
  margin-top: 28px;
}
::v-deep .el-tabs__content {
  border-left: 1px solid #e8e8e8;
  padding-left: 36px;
}
::v-deep.el-tabs--left .el-tabs__header.is-left {
  margin-right: 0;
}
::v-deep.el-tabs--left .el-tabs__item.is-left {
  text-align: left;
}
::v-deep .el-tabs__item {
  height: 48px;
}
.rightBtns {
  float: right;
}
.titleFlag {
  width: 4px;
  height: 18px;
  border-radius: 32px;
  background-color: #409eff;
  margin-right: 12px;
}
</style>
